import 'dart:convert';
import 'dart:developer' as developer;

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import 'models/economic_model.dart';

class EconomicDate extends StatelessWidget {
  const EconomicDate({super.key});

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getData(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData != false) {
            return Table(
                border: TableBorder.all(),
                columnWidths: const <int, TableColumnWidth>{
                  0: IntrinsicColumnWidth(),
                  1: FlexColumnWidth(),
                  2: FixedColumnWidth(64),
                },
                defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                children: <TableRow>[
                  TableRow(
                      decoration: ShapeDecoration(
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(0)),
                          color: Colors.blue),
                      children: const [
                        TableCell(
                            child: Text('名称', textAlign: TextAlign.center)),
                        TableCell(
                            child: Text('值', textAlign: TextAlign.center)),
                        TableCell(
                            child: Text('年份', textAlign: TextAlign.center)),
                      ]),
                  ...snapshot.data
                      .map((e) => TableRow(children: [
                            TableCell(
                                child: Text(e.zb, textAlign: TextAlign.center)),
                            TableCell(
                                child:
                                    Text(e._data, textAlign: TextAlign.center)),
                            TableCell(
                                child: Text(e.sj, textAlign: TextAlign.center))
                          ]))
                      .toList()
                      .cast<TableRow>()
                ]);
          } else {
            return const Text("数据请求中");
          }
        });
  }

  Future<List<NationData>> getData() async {
    List<NationData> res = [];
    res.addAll(await getGdpData());
    res.addAll(await getPmiData());
    res.addAll(await getCPIData());
    res.addAll(await getPPIData());
    return res;
  }

  Future<List<NationData>> getGdpData() async {
    // 过滤想看的经济指标
    final List<String> economicItems = [
      '国内生产总值(不变价)_当季值(亿元)',
      '国内生产总值环比增长速度(%)',
      '国内生产总值指数(上年同期=100)_当季值',
      '国内生产总值增长(百分点)',
      '国内生产总值指数(上年=100)'
    ];
    // 查询两页数据
    List<NationData> economicData =
        await _httpGetData('GDP', ['0', '1'], economicItems);
    // 将季度数据放前面，年度数据放后面
    economicData.sort((l, r) => l.sj.contains('季') ? -1 : 1);
    return economicData;
  }

  /// 向国家数据请求数据
  /// filter 代表要过滤的数据内容
  Future<List<NationData>> _httpGetData(
      String searchName, List<String> pages, List<String> filter) async {
    developer.log('请求国家数据中，请求内容：$searchName，请求页数 $pages，过滤内容：$filter');
    List<NationData> httpRes = [];
    // 查询两页数据
    for (var p in pages) {
      var url = Uri.https('data.stats.gov.cn', '/search.htm',
          {'s': searchName, 'm': 'searchdata', 'db': '', 'p': p});
      var response = await http.get(url);
      EconomicModel economicModel =
          EconomicModel.fromJson(jsonDecode(response.body));
      httpRes.addAll(economicModel.result);
    }
    developer.log('请求国家原生结果：$httpRes');
    List<NationData> uniqueDtaRes = [];
    // 删除重复数据
    for (NationData gdpData in httpRes) {
      // 如果数据不重复
      if (!_isDuplicated(uniqueDtaRes, gdpData)) {
        uniqueDtaRes.add(gdpData);
      }
    }

    // 过滤出想要的数据
    List<NationData> res = [];
    for (NationData gdpData in uniqueDtaRes) {
      // 如果 filter 为空，说明全都要！
      if (filter.isEmpty || filter.contains(gdpData.zb)) {
        res.add(gdpData);
      }
    }
    developer.log('国家数据结果：$res');
    return res;
  }

  Future<List<NationData>> getPmiData() async {
    List<NationData> economicData =
        await _httpGetData('综合PMI产出指数', ['0'], ['综合PMI产出指数(%)']);
    return economicData;
  }

  // 大于3%即将通货膨胀，持续5%以上说明严重的通货膨胀
  Future<List<NationData>> getCPIData() async {
    List<NationData> economicData = await _httpGetData(
        'CPI', ['0'], ['居民消费价格指数(上月=100)', '居民消费价格指数(上年同月=100)']);
    return economicData;
  }

  Future<List<NationData>> getPPIData() async {
    List<NationData> economicData = await _httpGetData(
        'PPI', ['0'], ['工业生产者出厂价格指数(上年=100)', '工业生产者出厂价格指数(上月=100)']);
    return economicData;
  }

  // 国家数据 api 存在重复数据，需要过滤
  bool _isDuplicated(List dataList, NationData newData) {
    for (NationData data in dataList) {
      if (data.zb == newData.zb && data.sj == newData.sj) {
        return true;
      }
    }
    return false;
  }
}
